package com.qf.service.impl;

import org.springframework.util.StringUtils;
import com.qf.bean.User;

import com.qf.dao.UserDao;
import com.qf.service.UserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    //校验用户名是否可用
    @Override
    public Integer checkUsername(String username) {
        //健壮性判断，避免username为空串
        if(!StringUtils.isEmpty(username)){
            username=username.trim();
        }
        //调用dao查询数据条数
        Integer count=userDao.findCountByUsername(username);
//        返回数据
        return count;
    }

//   注册账号
    @Override
    @Transactional
    public Integer register(User user) {
        //1.给密码加密
        String md5Pwd = new Md5Hash(user.getPassword()).toString();
        user.setPassword(md5Pwd);
        //调用dao保存
        return userDao.save(user);
    }

    @Override
    public User login(String username, String password) {
        //1.调用dao根据用户查询用户信息
        User user = userDao.findByUsername(username);
        //2.判断用户名是否正确
        if(user !=null) {
            //3.判断密码是否正确
            if(user.getPassword().equals(new Md5Hash(password).toString())){
                //用户名和密码都正确
                return  user;
            }
        }
        //用户名或密码错误
        return null;
    }
//    @Autowired
//    private UserDao userDao;
//    @Override
//    public Integer findCount() {
//        return userDao.findCount();

//    }

}
